package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.UserTrajectorySearchDTO;
import org.springblade.modules.admin.enums.BuildingCacheEnum;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.IUserTrajectoryService;
import org.springblade.modules.admin.vo.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author: Sharry
 * @createTime: 2023/4/26 15:35
 * @version: Version-1.0
 */
@Slf4j
@RestController
@RequestMapping("/trajectory")
@AllArgsConstructor
@Api(tags = "人员轨迹接口",value = "/trajectory")
public class UserTrajectoryController {

	private final IUserTrajectoryService uts;

	private final BuildingService buildingService;

	private final BladeRedis bladeRedis;


	/**
	 * 添加项目列表缓存,预留接口
	 */
	@GetMapping("/cache")
	@ApiOperation("添加项目列表缓存")
	@ApiOperationSupport(order = 11)
	public R<Object> test(){
		// 组合 key ： 前缀 + 租户id
		String prefix = BuildingCacheEnum.BUILDING_REDIS_LIST.getKey();
		String tenantId = AuthUtil.getTenantId();
		String key = prefix + tenantId;
		// 获取目标对象列表
		List<BuildingRedisVO> buildingList = buildingService.listForVO();
		bladeRedis.del(key);
		// 执行
		buildingList.forEach(b -> bladeRedis.lPush(key,b));
		Object[] redisBuildings = bladeRedis.lRange(key, 0, -1).toArray();
		return R.data(redisBuildings);
	}

	/**
	 * 组-人下拉列表
	 * @return 组-人下拉列表
	 */
	@GetMapping("/people")
	@ApiOperation("组-人下拉列表")
	@ApiOperationSupport(order = 20)
	public R<List<UserTrajectoryQueryVO>> getUserList(){
		//当前租户
		String tenantId = AuthUtil.getTenantId();
		List<UserTrajectoryQueryVO> userList = uts.getUserList(tenantId);
		return R.data(userList);
	}


	/**
	 * 人员轨迹 分页
	 * @param userTrajectorySearchDTO 查询条件
	 * @param current 当前页
	 * @param size 每页大小
	 * @return 人员轨迹分页列表
	 */
	@PostMapping("/trajectory/search")
	@ApiOperation("人员轨迹分页")
	@ApiOperationSupport(order = 21)
	public R<UserTrajectoryCountVO> getTrajectoryList(@RequestBody UserTrajectorySearchDTO userTrajectorySearchDTO, Integer current, Integer size){
		// 获取 人员轨迹分页列表
		List<UserTrajectoryVO> userTrajectoryVOList = uts.getUserTrajectoryVOList(userTrajectorySearchDTO);

		// 统计并手动分页
		UserTrajectoryCountVO userTrajectoryCountVO = uts.getUserTrajectoryCount(userTrajectorySearchDTO, userTrajectoryVOList, current, size);
		if(null == userTrajectoryCountVO.getTotal()){
			userTrajectoryCountVO.setTotal(0);
		}
		if(Func.isEmpty(userTrajectoryVOList)){
			userTrajectoryCountVO.setUserTrajectoryVOList(new ArrayList<UserTrajectoryVO>());
		}
		// 统计结果返回
		return R.data(userTrajectoryCountVO);
	}


	@GetMapping("/test")
	@ApiOperation("测试")
	@ApiOperationSupport(order = 22)
	public void t() {
		uts.list();
	}

	@GetMapping("/daily-work-time")
	@ApiOperation("计算用户每日在线和离线时长")
	@ApiOperationSupport(order = 23)
	public R<List<UserTrajectoryVO>> calculateUserDailyWorkTime(
		@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
		@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
		List<UserTrajectoryVO> result = uts.calculateUserDailyWorkTime(beginTime, endTime);
		return R.data(result);
	}

	@GetMapping("/user/day")
	@ApiOperation("计算用户每日在线和离线时长")
	@ApiOperationSupport(order = 24)
	public R<List<UserTrajectoryVO>> calculateUserDayCount(
		@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
		@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
		List<UserTrajectoryVO> result = uts.calculateUserDayCount(beginTime, endTime);
		return R.data(result);
	}

	@ApiOperation("下载明细")
	@GetMapping("/user/day/down/excel")
	public void downExcelDetail(HttpServletResponse response, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
								@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) throws IOException {
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList
				("人员ID", "人员姓名", "手机系统","日期", "总计上报次数","在线时长", "APP上报次数", "小程序上报次数", "第一次上报时间",
					"最后一次上报时间", "APP工单数（签到签退都在APP）", "小程序工单数（签到签退都在小程序）");
			rows.add(title);
			uts.downExcelDetail(beginTime,endTime, rows);
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			CommonUtil.setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}

	}


}
